package com.atguigu.gmall.mq.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author mqx
 * @date 2020-11-20 14:27:05
 */
@RestController
@RequestMapping("/mq")
public class MqController {

    //  获取发送消息的工具类
    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //  发送消息
    @RequestMapping("sendConfirm")
    public Result sendMsg(){
        //  发送数据。
        rabbitService.sendMessage("exchange.confirm","routing.confirm666","OK");
        return Result.ok();
    }

    @GetMapping("sendDeadLettle")
    public Result sendDeadLettle(){
        //  声明一个时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //  发送消息
        rabbitService.sendMessage(DeadLetterMqConfig.exchange_dead,DeadLetterMqConfig.routing_dead_1,simpleDateFormat.format(new Date()));

        System.out.println("消息发送了：\t"+simpleDateFormat.format(new Date()));

        return Result.ok();
    }

    //  基于插件的延迟消息
    @GetMapping("sendDelay")
    public Result sendDelay(){
        //  声明一个时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //  设置发送消息 ,但是你的延迟时间呢?  不能使用该方法！
        //  rabbitService.sendMessage(DelayedMqConfig.exchange_delay,DelayedMqConfig.routing_delay,simpleDateFormat.format(new Date()));

        rabbitTemplate.convertAndSend(DelayedMqConfig.exchange_delay, DelayedMqConfig.routing_delay, "来人了，开始接客了！", new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //  设置延迟时间
                message.getMessageProperties().setDelay(10000);
                //  打印发送时间
                System.out.println("消息发送了：\t"+simpleDateFormat.format(new Date()));
                return message;
            }
        });
        return Result.ok();
    }
}
